/*
 * @Author: wangc
 * @Date: 2020-07-28 19:33:23
 * @LastEditTime: 2020-08-30 15:57:13
 * @LastEditors: Please set LastEditors
 * @Description: 封装一下axios，主要做了：
 * 1.设置请求的域名和请求超时时间
 * 2.请求拦截，对参数用qs处理一下
 */ 
import axios from 'axios' //引入 axios
import qs from "qs"

// 创建 axios 实例
const service = axios.create({
  baseURL: "http://localhost:8081", // api 的 base_url
  timeout: 15000, // 请求超时时间
})
service.interceptors.request.use(
  config => {
    if(localStorage.getItem('token')){
      config.headers.token = localStorage.getItem('token');
    }
    config.headers = {
      //消灭options请求
      'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', //  注意：设置很关键 
      'token':localStorage.getItem('token')?localStorage.getItem('token'):""
    }
    // 根据请求方法，序列化传来的参数，根据后端需求是否序列化
    if (config.method.toLocaleLowerCase() === 'post' ||
      config.method.toLocaleLowerCase() === 'put' ||
      config.method.toLocaleLowerCase() === 'delete') {
      config.data = qs.stringify(config.data);
    }
    return config
  },
  err => {
    return Promise.reject(err)
  }
)
export default service